package com.admin.system.auth.service;

import com.admin.system.common.SystemConstant;
import com.admin.system.entity.SystemUser;
import com.admin.system.service.SystemUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.admin.system.auth.entity.LoginToken;

@Service
public class AccoutAuthService {
    private static final Logger logger = LoggerFactory.getLogger(AccoutAuthService.class);
    @Autowired
    SystemUserService userService;

    public SystemUser checkLoginToken(LoginToken token) {
        SystemUser user = userService.queryByUserName(token.getUserName());
        if (user == null) {
            throw new UnknownAccountException("unknown account...");
        } else {
            // 禁用账号
            if (user.getStatus().equals(SystemConstant.UserStatus.UNUSABLE.getCode())) {
                logger.info("账号已禁用：[{}]", user.getName());
                throw new DisabledAccountException("disabled account...");
            }
            //
            String loginPwd = DigestUtils.md5Hex(token.getUserName() + token.getPassword());
            if (!loginPwd.equals(user.getPassword())) {
                throw new CredentialsException("wrong credentials...");
            }
        }
        return user;
    }
}
